<?php
/**
 * GioCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@ninhgio.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2010-2011 GioCMS (http://cms.ninhgio.com)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @author		NinhGio - ninhgio@gmail.com
 * @since		1.0
 */

class Gio_Core_Messenger
{
	private $_messages = array();
	private $_name = 'messages';
	
	public function __construct()
	{
		if (isset($_SESSION[$this->_name])) {
			$this->_messages = $_SESSION[$this->_name]; 
		} else {
			$_SESSION[$this->_name] = $this->_messages;
		}
	}
	
	/**
	 * @return Gio_Core_Messenger
	 */
	public static function getInstance()
	{
		return new self();
	}
	
	public function addMessage($message)
	{
		$this->_messages[] = $message;
		$_SESSION[$this->_name] = $this->_messages; 
	}
	
	public function getMessages()
	{
		return $this->_messages;	
	}
	
	public function printMessages($format = true)
	{
		if (empty($this->_messages)) {
			return null;
		}
		$string = '';
		if ($format) {
			$string = '<div class="g_a_message"><ul>';
			foreach ($this->_messages as $index => $message) {
				$string .= '<li><b>' . $message . '</b></li>';
			}
			$string .= '</ul></div>';
		} else {
			foreach ($this->_messages as $index => $message) {
				$string .= $message;
			}
		}
		$this->clear();
		return $string; 
	}
	
	public function clear()
	{
		unset($_SESSION[$this->_name]);
	}
}